﻿using System;
using System.Collections.Generic;

using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace Kwan.Core
{
    public class DESCrypto
    {

        private RasCrypto mPublicRas = new RasCrypto();
        private RasCrypto mPrivateRas = new RasCrypto();
        private DESCryptoServiceProvider key = new DESCryptoServiceProvider();
        public DESCrypto()
        {
        }
        public DESInfo KeyInfo
        {
            get
            {
                DESInfo info = new DESInfo();
                info.Key = mPublicRas.Encrypt(key.Key);
                info.IV = mPublicRas.Encrypt(key.IV);
                return info;
            }
            set
            {
                key.Key = mPrivateRas.Decrypt(value.Key);
                key.IV = mPrivateRas.Decrypt(value.IV);
            }
        }
        public void CopyRasParameters(DESCrypto descrypto)
        {
            mPrivateRas.CopyRSAParameters(false, descrypto.PublicRas);
        }
        public RasCrypto PrivateRas
        {
            get
            {
                return mPrivateRas;
            }
        }
        public RasCrypto PublicRas
        {
            get
            {
                return mPublicRas;
            }
        }
        public class DESInfo
        {
            public byte[] Key { get; set; }
            public byte[] IV { get; set; }
        }
        public string Encrypt(string data)
        {
            return Convert.ToBase64String(Encrypt(System.Text.Encoding.UTF8.GetBytes(data)));
        }
        public byte[] Encrypt(byte[] data)
        {

            MemoryStream ms = new MemoryStream();
            CryptoStream encStream = new CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write);
            encStream.Write(data, 0, data.Length);
            encStream.Close();
            byte[] buffer = ms.ToArray();
            ms.Close();
            return buffer;
        }
        public string Decrypt(string data)
        {
            return System.Text.Encoding.UTF8.GetString(Decrypt(Convert.FromBase64String(data)));
        }
        public byte[] Decrypt(byte[] data)
        {

            IList<byte> result = new List<byte>();
            int value;
            MemoryStream ms = new MemoryStream(data);
            CryptoStream encStream = new CryptoStream(ms, key.CreateDecryptor(), CryptoStreamMode.Read);
            value = encStream.ReadByte();
            while (value >= 0)
            {
                result.Add((byte)value);
                value = encStream.ReadByte();
            }
            encStream.Close();
            ms.Close();
            byte[] rdata = new byte[result.Count];
            result.CopyTo(rdata, 0);
            return rdata;

        }
    }
}
